import 'dart:convert';

import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:http/http.dart' as http;
import 'package:trip_flutter/dao/login_util.dart';

class LoginDao {
  static const boardingPass = "boarding_pass";

  static login(String userName, String password) async {
    Map<String, String> params = {};
    params["userName"] = userName;
    params["password"] = password;
    Uri uri = Uri.parse("https://api.geekailab.com/uapi/user/login");
    var response = await http.post(uri, headers: hiHeaders(), body: params);

    /// 防止中文乱码
    Utf8Decoder utf8decoder = const Utf8Decoder();
    String bodyString = utf8decoder.convert(response.bodyBytes);
    print(bodyString);

    if (response.statusCode == 200) {
      var result = json.decode(bodyString);
      if (result['code'] == 0 && result['data'] != null) {
        // 保存登录令牌
        _saveBoardingPass(result['data']);
      } else {
        throw Exception(bodyString);
      }
    } else {
      throw Exception(bodyString);
    }
  }

  static void _saveBoardingPass(String value) {
    HiCache.getInstance().setString(boardingPass, value);
  }

  static getBoardingPass() {
    return HiCache.getInstance().get(boardingPass);
  }
}
